package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //判断用户是否登录,登录过,放行
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;


        //获取本次URI
        String requestURI = request.getRequestURI();
        log.info("拦截到请求" + requestURI);


        //定义不需要被拦截的路径
        //"/employee/login"
        //"/employee/logout"
        //"/backend/**"
        //"/front/**"

        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "**/*.ico",
                "/user/login",
                "/user/sendMsg"
        };

        for (String url : urls) {
            if (PATH_MATCHER.match(url, requestURI)) {
                //放行
                log.info("请求访问公开地址通过");
                filterChain.doFilter(request, response);
                return;
            }

        }

        //判断是否登录
        if (request.getSession().getAttribute("employee") != null) {
            //存在session,放行
            log.info("存在session,放行");

            //LoginCheckFilter中存放当前登录用户到ThreadLocal
            Employee employee = (Employee) request.getSession().getAttribute("employee");
            BaseContext.setThreadLocal(employee.getId());


            filterChain.doFilter(request, response);
            return;
        }
        if (request.getSession().getAttribute("user") != null) {
            //存在session,放行
            log.info("存在session,放行");

            //LoginCheckFilter中存放当前登录用户到ThreadLocal
            User user = (User) request.getSession().getAttribute("user");
            BaseContext.setThreadLocal(user.getId());


            filterChain.doFilter(request, response);
            return;
        }


        //没登录不放行,跳转
        log.info("用户未登录");
        R notlogin = R.error("NOTLOGIN");
        String json = JSON.toJSONString(notlogin);
        response.getWriter().write(json);
    }


    @Override
    public void destroy() {
        BaseContext.removeThreadLocal();
    }
}
